import uuid
import contextvars
from typing import Optional

# 定义上下文变量，默认值为 None
_request_id_context: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
    "request_id", default=None
)

def get_request_id() -> Optional[str]:
    """获取当前上下文的 request_id"""
    return _request_id_context.get()

def set_request_id(request_id: Optional[str]) -> None:
    """设置当前上下文的 request_id"""
    _request_id_context.set(request_id)

def generate_request_id() -> str:
    """生成新的 request_id（UUID 格式）"""
    return str(uuid.uuid4())